package com.lc.railway.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.base.BaseDialog;
import com.lc.railway.R;
import com.lc.railway.app.AppActivity;
import com.lc.railway.bean.StockEntity;
import com.lc.railway.http.request.PopularApi;
import com.lc.railway.http.request.SearchApi;
import com.lc.railway.http.response.ReturnhotWordsBean;
import com.lc.railway.http.response.SearchBean;
import com.lc.railway.other.KeyboardWatcher;
import com.lc.railway.sqlite.RecordsDao;
import com.lc.railway.ui.dialog.MessageDialog;
import com.lc.railway.util.FindUtil;
import com.lc.widget.layout.SettingBar;
import com.lc.widget.view.ClearEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends AppActivity implements KeyboardWatcher.SoftKeyboardStateListener,
        TextView.OnEditorActionListener{
    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;

    @BindView(R.id.title_bar_txt_right)
    TextView titleBarTxtRight;
    @BindView(R.id.rl_layout_focus)
    RelativeLayout rlLayoutFocus;
    @BindView(R.id.rv_popular_searches)
    RecyclerView rvPopularSearches;
    @BindView(R.id.rv_searchRecords)
    RecyclerView rvSearchRecords;
    @BindView(R.id.ll_searchRecords)
    LinearLayout llSearchRecords;


    List<SearchBean.DataBeanX.DataBean> datas = new ArrayList<>();
    List<String> dataPopularBeanList = new ArrayList<>();
    @BindView(R.id.tv_searchRecords)
    TextView tvSearchRecords;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.sb_honor)
    SettingBar sbHonor;
    @BindView(R.id.rv_importantnews)
    RecyclerView rvImportantnews;
    @BindView(R.id.ll_search_content)
    LinearLayout llSearchContent;

    private BaseQuickAdapter<StockEntity, BaseViewHolder> seachHistoryAdapter;
    private BaseQuickAdapter<String, BaseViewHolder> popularadapter;
    private BaseQuickAdapter<SearchBean.DataBeanX.DataBean, BaseViewHolder>  searchadapter;
    private List<StockEntity> searchRecordsList;
    private List<StockEntity> tempList;
    private RecordsDao recordsDao;
    private static final String TAG = "SearchActivity";
    private String keyword;
    private String canteenid = "0";
    private int total;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        etSearch.setOnEditorActionListener(this);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(TextUtils.isEmpty(etSearch.getText().toString().trim())){
                    llSearch.setVisibility(View.VISIBLE);
                    llSearchContent.setVisibility(View.GONE);
                }
            }
        });
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
                layoutManager.setFlexDirection(FlexDirection.ROW);
                layoutManager.setJustifyContent(JustifyContent.FLEX_START);
                rvPopularSearches.setLayoutManager(layoutManager);
                popularadapter = new BaseQuickAdapter<String, BaseViewHolder>
                        (R.layout.item_home_search,dataPopularBeanList) {

                    @Override
                    protected void convert(BaseViewHolder baseViewHolder,String dataBean) {
                        baseViewHolder.setText(R.id.tv_search_records,dataBean);
                    }


                };
        rvPopularSearches.setAdapter(popularadapter);
//热门
        searchPopular();
        /**
         *   历史记录数据
         */

        recordsDao = new RecordsDao(this);
        searchRecordsList = new ArrayList<>();
        tempList = new ArrayList<>();
        tempList.addAll(recordsDao.findAll());
        Log.e(TAG, "initData: " + tempList.size());
        reversedList();
        //第一次进入判断数据库中是否有历史记录，没有则不显示
        checkRecordsSize();
//         历史记录
        searchrecords();
        searchadapter=new BaseQuickAdapter<SearchBean.DataBeanX.DataBean, BaseViewHolder>(R.layout.item_test) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, SearchBean.DataBeanX.DataBean jiangliBean) {

TextView tv_title=holder.getView(R.id.tv_title);
              FindUtil.setTextHighLight(tv_title,keyword,jiangliBean.getTitle());
                holder.setText(R.id.tv_date,jiangliBean.getCreate_time());
            }
        };
        rvImportantnews.setAdapter(searchadapter);
        View emptyview = View.inflate(this, R.layout.empty_emptylayout, null);
        searchadapter.setEmptyView(emptyview);

    }

    @Override
    protected void onStart() {
        super.onStart();
       llSearch.setVisibility(View.VISIBLE);
       llSearchContent.setVisibility(View.GONE);
    }

    private void searchrecords() {

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rvSearchRecords.setLayoutManager(layoutManager);

            seachHistoryAdapter = new BaseQuickAdapter<StockEntity, BaseViewHolder>
                    (R.layout.item_home_search, searchRecordsList) {

                @Override
                protected void convert(BaseViewHolder baseViewHolder, StockEntity dataBean) {
                    baseViewHolder.setText(R.id.tv_search_records, dataBean.getName());
                }


            };
            rvSearchRecords.setAdapter(seachHistoryAdapter);

        seachHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                keyword=searchRecordsList.get(position).getName();
                etSearch.setText(searchRecordsList.get(position).getName());
                search(searchRecordsList.get(position).getName());

            }
        });

    }
    private void searchPopular() {

        EasyHttp.post(this)
                .api(new PopularApi()).request(new HttpCallback<ReturnhotWordsBean>(this) {

            @Override
            public void onSucceed(ReturnhotWordsBean data) {
//
                dataPopularBeanList.clear();
                dataPopularBeanList.addAll(data.getData());
                popularadapter.setNewData(dataPopularBeanList);
                popularadapter.notifyDataSetChanged();
               popularadapter.setOnItemClickListener(new OnItemClickListener() {
                   @Override
                   public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                       keyword=dataPopularBeanList.get(position);
                       etSearch.setText(dataPopularBeanList.get(position));
                       search(dataPopularBeanList.get(position));
                       if (!recordsDao.isHasRecord(dataPopularBeanList.get(position))) {
                           //将搜索记录保存至数据库中
                           recordsDao.add(dataPopularBeanList.get(position),"");
                       }
                       tempList.clear();

                       tempList.addAll(recordsDao.findAll());
                       reversedList();
                       checkRecordsSize();
                       seachHistoryAdapter.notifyDataSetChanged();

                   }
               });

            }

        });
//
    }

    //当没有匹配的搜索数据的时候不显示历史记录栏
    private void checkRecordsSize() {
        if (searchRecordsList.size() == 0) {
            llSearchRecords.setVisibility(View.GONE);
        } else {
            llSearchRecords.setVisibility(View.VISIBLE);
        }
    }


    //颠倒list顺序，用户输入的信息会从上依次往下显示
    private void reversedList() {
        searchRecordsList.clear();
        for (int i = tempList.size() - 1; i >= 0; i--) {
            searchRecordsList.add(tempList.get(i));
        }
    }
    private void search(String trim) {
        llSearch.setVisibility(View.GONE);
        llSearchContent.setVisibility(View.VISIBLE);
        EasyHttp.post(this)
                .api(new SearchApi().setSearch(trim))
                .request(new HttpCallback<SearchBean>(this) {
                    @Override
                    public void onSucceed(SearchBean data) {
//
                        if (data.getError_code() == 200) {
                            datas.clear();
                            datas.addAll(data.getData().getData());
                            total = data.getData().getTotal();
                            searchadapter.setNewData(datas);
                            searchadapter.notifyDataSetChanged();

                        }
                    }
                });
    }

    @OnClick({R.id.rl_search, R.id.title_bar_txt_right, R.id.tv_searchRecords})
    public void onClick(View view) {
        switch (view.getId()) {


            case R.id.title_bar_txt_right:
                finish();
                break;
            case R.id.tv_searchRecords:
//                删除历史记录
                new MessageDialog.Builder(getActivity())
                        // 标题可以不用填写
                        .setTitle("提示")
                        // 内容必须要填写
                        .setMessage("是否清空全部历史搜索记录")
                        // 确定按钮文本
                        .setConfirm(getString(R.string.common_confirm))
                        // 设置 null 表示不显示取消按钮
                        .setCancel(getString(R.string.common_cancel))
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener(new MessageDialog.OnListener() {

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                tempList.clear();
                                reversedList();
                                recordsDao.deleteAllRecords();
                                seachHistoryAdapter.notifyDataSetChanged();
                                llSearchRecords.setVisibility(View.GONE);
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {
                                dialog.dismiss();
                            }
                        })
                        .show();

                break;
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 模拟点击登录按钮
            keyword=etSearch.getText().toString().trim();
            search(etSearch.getText().toString().trim());
//            搜索

            if (!recordsDao.isHasRecord(etSearch.getText().toString().trim())) {
                //将搜索记录保存至数据库中
                recordsDao.add(etSearch.getText().toString().trim(),"");
            }
            tempList.clear();

            tempList.addAll(recordsDao.findAll());
            reversedList();
            checkRecordsSize();
            seachHistoryAdapter.notifyDataSetChanged();
            return true;
        }
        return false;
    }


    @Override
    public void onSoftKeyboardOpened(int keyboardHeight) {

    }

    @Override
    public void onSoftKeyboardClosed() {

    }
}
